<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        border: solid;
        height: 400px;
        width: 400px;
        margin: 200px 0 0 300px;
        position: relative;
      }

      #ball {
        width: 100px;
        height: 100px;
        background: grey;
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div id="box">
      <div id="ball"></div>
    </div>
    <script>
      const box = document.getElementById("box");
      const ball = document.getElementById("ball");

      box.onclick = function (e) {
        // 获取鼠标距离box右上角坐标
        const pos = box.getBoundingClientRect();
        const x = e.clientX - pos.x;
        const y = e.clientY - pos.y;
        // 将ball的left和top设置成坐标值
        ball.style.left = x - ball.offsetWidth / 2 + "px";
        ball.style.top = y - ball.offsetHeight / 2 + "px";

        // 判断是否越过左边
        if (e.clientX - pos.x < ball.offsetWidth / 2) {
          // 如果越界设置left=0 right=''
          ball.style.left = 0;
          ball.style.right = "";
        }

        // 判断是否越过顶边
        if (e.clientY - pos.y < ball.offsetHeight / 2) {
          // 如果越界设置top=0 bottom=''
          ball.style.top = 0;
          ball.style.bottom = "";
        }

        if (pos.right - e.clientX < ball.offsetWidth / 2) {
          // 如果越界设置left='' right=0
          ball.style.left = "";
          ball.style.right = 0;
        }

        if (pos.bottom - e.clientY < ball.offsetWidth / 2) {
          // 如果越界设置bottom=0 top=''
          ball.style.top = "";
          ball.style.bottom = 0;
        }
      };
    </script>
  </body>
</html>
